// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.trees.expressions.functions.scalar;

import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.NeedSessionVarGuard;
import org.apache.doris.nereids.trees.expressions.functions.CustomSignature;
import org.apache.doris.nereids.trees.expressions.functions.ExpressionTrait;
import org.apache.doris.nereids.trees.expressions.functions.SearchSignature;
import org.apache.doris.nereids.trees.expressions.literal.Literal;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.util.ExpressionUtils;
import org.apache.doris.nereids.util.TypeCoercionUtils;

import com.google.common.base.Preconditions;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * ScalarFunction 'coalesce'. This class is generated by GenerateFunction.
 */
public class Coalesce extends ScalarFunction implements CustomSignature, NeedSessionVarGuard {

    /**
     * constructor with 1 or more arguments.
     */
    public Coalesce(Expression arg, Expression... varArgs) {
        super("coalesce", ExpressionUtils.mergeArguments(arg, varArgs));
    }

    /** constructor for withChildren and reuse signature */
    private Coalesce(ScalarFunctionParams functionParams) {
        super(functionParams);
    }

    /**
     * custom compute nullable.
     */
    @Override
    public boolean nullable() {
        for (Expression argument : children) {
            if (!argument.nullable()) {
                return false;
            }
        }
        return true;
    }

    /**
     * withChildren.
     */
    @Override
    public Coalesce withChildren(List<Expression> children) {
        Preconditions.checkArgument(!children.isEmpty());
        return new Coalesce(getFunctionParams(children));
    }

    @Override
    public FunctionSignature customSignature() {
        Map<Boolean, List<Expression>> partitioned = getArguments().stream()
                .collect(Collectors.partitioningBy(
                        e -> (e instanceof Literal && ((Literal) e).isStringLikeLiteral())));
        List<DataType> forFindCommon = partitioned.get(false).stream()
                .map(ExpressionTrait::getDataType)
                .collect(Collectors.toList());
        Optional<DataType> commonType = TypeCoercionUtils.findWiderCommonTypeByVariable(forFindCommon, false, true);
        if (!commonType.isPresent()) {
            SearchSignature.throwCanNotFoundFunctionException(this.getName(), getArguments());
            return null;
        } else {
            for (Expression stringLiteral : partitioned.get(true)) {
                Optional<Expression> option = TypeCoercionUtils.characterLiteralTypeCoercion(
                        ((Literal) stringLiteral).getStringValue(), commonType.get());
                if (!option.isPresent()) {
                    commonType = TypeCoercionUtils.findWiderTypeForTwo(
                            commonType.get(), stringLiteral.getDataType(), false, true);
                    if (!commonType.isPresent()) {
                        SearchSignature.throwCanNotFoundFunctionException(this.getName(), getArguments());
                    } else {
                        break;
                    }
                }
            }
            return FunctionSignature.ret(commonType.get()).varArgs(commonType.get());
        }
    }

    @Override
    public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
        return visitor.visitCoalesce(this, context);
    }
}
